<template>
  <div>
    <pro-table :columns="columns" :request="fetchFourTypes" row-key="id" 
     :form-ref="setFormRef"
     :pagination="false"
     :defaultFormData="{name:''}"
     header-title=""
      :action-ref="setActionRef">
      <template #option-render="{ dom }">
        <a-button key="primary" type="primary" v-auth="'createClassifyBtn'" @click="showAddModal">创建分类</a-button>
        <a-button key="primary" type="primary" v-auth="'exportClassifyBtn'" @click="handleImport">导入</a-button>
        <a-button key="primary" type="primary" v-auth="'importClassifyBtn'" @click="handleExport">导出</a-button>
      </template>
      <template #action="{ record }">
        <a-button v-auth="'classifyEidtBtn'" type="text" @click="handleDetail(record.id)">编辑</a-button>
        <a-popconfirm content="确认删除么"  @ok="handleDelete(record.id)">
          <a-button  v-auth="'classifyDelBtn'" type="text" status="danger" >删除</a-button>
        </a-popconfirm>
      </template>
    </pro-table>

    <!-- 详情模态框 -->
    <a-modal v-model:visible="detailVisible" title="四级分类详情">
      <p>{{ detail.name }}</p>
      <p>{{ detail.info }}</p>
      <p>{{ detail.status }}</p>
    </a-modal>

    <!-- 添加分类模态框 -->
    <a-modal v-model:visible="addModalVisible" title="创建四级分类" @ok="handleAdd">
      <a-form :model="newFourType" layout="vertical">
        <a-form-item label="名称" :rules="[{ required: true, message: '名称' }]">
          <a-input v-model="newFourType.name" placeholder="请输入名称" />
        </a-form-item>
        <a-form-item label="描述">
          <a-input v-model="newFourType.info" placeholder="请输入描述" />
        </a-form-item>
        <a-form-item label="是否使用">
          <a-select v-model="newFourType.status">
            <a-option :value="1">否</a-option>
            <a-option :value="0">是</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="父级分类">
          <a-tree-select     :filter-tree-node="filterTreeNode" :allow-search="true" allow-clear v-model="newFourType.parentId" style="width: 100%" :data="treeData" tree-default-expand-all
            :field-names="{ key: 'id', title: 'name' }" placeholder="请选择父级分类"  />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 导入文件输入控件 -->
    <input type="file" ref="fileInput" style="display: none;" @change="handleFileChange" />
  </div>
</template>

<script lang="ts">
import { Ref, defineComponent, ref } from 'vue';
import {
  getFourTypeList,
  deleteFourType,
  getFourTypeDetail,
  saveFourType,
  importFourType, 
  exportFourType, 
} from '@/api/foutType';
import { TreeNodeData } from '@arco-design/web-vue/es/tree/interface';
import Message from '@arco-design/web-vue/es/message';

export default defineComponent({
  name: 'FourTypePage',
  setup() {
    const formRef = ref();
    const actionRef = ref();
    const fileInput = ref<HTMLInputElement | null>(null);

    const setFormRef = (ref: Ref) => {
      formRef.value = ref;
    };
    const setActionRef = (ref: Ref) => {
      actionRef.value = ref;
    };

    const columns = [
      { title: '分类ID', dataIndex: 'id', hideInSearch: true },
      { title: '分类', dataIndex: 'name', hideInSearch: true },
      { title: '描述', dataIndex: 'info', hideInSearch: true },
      {
        title: '是否使用', dataIndex: 'status', valueEnum: {
          1: { text: '否', status: 'Default' },
          0: { text: '是', status: 'Success' },
        }, hideInSearch: true
      },
      {
        title: '操作',
        dataIndex: 'action',
        slotName: 'action',
        width:180,
        hideInSearch: true
      },
    ];

    const pagination = ref({
      current: 1,
      pageSize: 10,
    });

    const detail = ref({
      name: '',
      info: '',
      status: 0,
    });

    const detailVisible = ref(false);
    const addModalVisible = ref(false);

    const newFourType = ref({
      name: '',
      info: '',
      status: 0,
      parentId: 0
    });
    const  filterTreeNode = (searchValue, nodeData)=> {
        return nodeData.name.toLowerCase().indexOf(searchValue.toLowerCase()) > -1;
      }
    const treeData = ref<TreeNodeData[]>([]);

    const fetchFourTypes = async (params: {
      current: number;
      pageSize: number;
      name: string;
    }) => {
      const response = await getFourTypeList(params.current, params.pageSize, '');
      treeData.value = [{ id: 0, name: '请选择父级' }, ...response.data];
      return {
        data: response.data,
        success: true,
        total: response.data.total
      };
    };

    const handleDelete = async (id: number) => {
      await deleteFourType(id);
      actionRef.value?.reload();
    };

    const handleDetail = async (id: number) => {
      const response = await getFourTypeDetail(id);
      newFourType.value = response.data;
      addModalVisible.value = true;
    };

    const showAddModal = () => {
      newFourType.value = {
        name: '',
        info: '',
        status: 0,
        parentId: 0
      };
      addModalVisible.value = true;
    };

    const handleAdd = async () => {
      const response = await saveFourType(newFourType.value);
      if (response) {
        addModalVisible.value = false;
        newFourType.value = {
          name: '',
          info: '',
          status: 0,
          parentId: 0
        };
        formRef.value.submit();
      }
    };

    const handleImport = () => {
      fileInput.value?.click();
    };

    const handleFileChange = async (event: Event) => {
      const file = (event.target as HTMLInputElement).files?.[0];
      if (file) {
        const formData = new FormData();
        formData.append('file', file);
        await importFourType(formData);
        Message.success('导入成功'); 
        actionRef.value?.reload();

      }
    };

    const handleExport = async () => {
      // exportFourType
      window.open('/service/demandFourType/downloadExcel', '_blank');
      // const response = await exportFourType('');
      // console.log(response, 'response')
      // const blob = new Blob([response.data], { type: 'application/octet-stream' });
      // const url = URL.createObjectURL(blob);
      // const link = document.createElement('a');
      // link.href = url;
      // link.download = 'four_types.csv';
      // document.body.appendChild(link);
      // link.click();
      // document.body.removeChild(link);
      // URL.revokeObjectURL(url);
    };

    return {
      columns,
      pagination,
      detail,
      detailVisible,
      addModalVisible,
      newFourType,
      fetchFourTypes,
      handleDelete,
      handleDetail,
      showAddModal,
      handleAdd,
      setFormRef,
      setActionRef,
      treeData,
      handleImport,
      handleFileChange,
      handleExport,
      fileInput,
      filterTreeNode
    };
  },
});
</script>